<?php
namespace app\common\controller;

use app\common\model\User as UserModel;
use app\common\model\Auth as AuthModel;
use think\facade\Config;
use think\Controller;
use think\facade\Request;
use think\facade\Validate;


class AdminBase extends Controller
{
    protected  $publicauth = ['admin/index/login','admin/index/logout','admin/index/noauth','admin/index/main'];
    protected $allowauth = ['admin/index/index','admin/index/userinfo'];
    public static $banmodules = ['admin','common'];

    protected static $AUTHLIST = array();

    protected function initialize()
    {
        $request = Request::instance();

        if( strtolower($request->module()) == 'publics')
            return true;

        $url = strtolower($request->module().'/'.$request->controller().'/'.$request->action());

        //什么都不需要验证
        if(in_array($url,$this->publicauth))
            return true;
        if(strstr($url,'test'))
            return true;

        //验证登录，同时保存用户ID
        if(!defined('UID')){
            $curr = UserModel::instance()->getLoginUser();
            if($curr){
                $this->assign('curruser',$curr);
                define('UID',$curr['id']);
            }else{
                $this->error('请登录',url('admin/index/login'));
            }
        }
        //获取权限列表
        if(empty(self::$AUTHLIST)){
            self::$AUTHLIST = AuthModel::instance()->getUserAuthList(UID);
        }

        if(in_array($url,$this->allowauth))
            return true;

        $btns = array();
        foreach(self::$AUTHLIST as $btn){
            $btns[$btn['action']] = $btn;
        }
        $this->assign('btns',$btns);
        //判断是否公共页面
        foreach(self::$AUTHLIST as $k=>$v){
            if( $v['action'] == $url){
                return true;
            }
        }
        //判断权限
        $this->error('无权限','','',3);
    }

    public function checkToken(){
        $data = [
            '__token__' => Request::param('__token__'),
        ];
        $rule = [
            '__token__' => 'require|max:32|token',
        ];
        $msg = [
            '__token__'  => '非法操作！',
        ];
        $validate = Validate::make($rule,$msg);
        if($validate->check($data))
            return true;
        else
            return $validate->getError();
    }
}
